<script setup>
import { ref, onMounted, reactive, computed, nextTick, onUnmounted } from 'vue'
import request,{ SERVER_BASE_URL } from '@/utils/request'
import { ElMessage } from 'element-plus'
import router from "@/router"

const listWrapper = ref(null)
const commodities = ref([])
const loading = ref(false)
const noMore = ref(false)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 12,
  name: '',
  status: 'ON_SALE', // 默认查询在售商品
  categoryTag: ''
})

// 获取商品列表 - 首次加载或刷新
const fetchCommodities = async () => {
  loading.value = true
  try {
    const response = await request.get(`/commodities/page?pageNum=${queryParams.pageNum}&pageSize=${queryParams.pageSize}&status=${queryParams.status}`)
    commodities.value = response.list || []
    // 判断是否还有更多数据
    if (commodities.value.length >= response.total) {
      noMore.value = true
    } else {
      noMore.value = false
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载更多商品
const loadMore = async () => {
  if (loading.value || noMore.value) {
    return
  }
  
  // console.log('v-infinite-scroll触发加载更多')
  queryParams.pageNum++
  loading.value = true
  
  try {
    const response = await request.get(`/commodities/page?pageNum=${queryParams.pageNum}&pageSize=${queryParams.pageSize}&status=${queryParams.status}`)
    const newItems = response.list || []
    
    if (newItems.length === 0) {
      noMore.value = true
      return
    }
    
    // 添加新数据到现有列表
    commodities.value = [...commodities.value, ...newItems]
    
    // 判断是否还有更多数据
    if (response.total && commodities.value.length >= response.total) {
      noMore.value = true
    }
  } catch (error) {
    ElMessage.error('加载更多商品失败')
    console.error(error)
    // 恢复页码
    queryParams.pageNum--
  } finally {
    loading.value = false
  }
}

// 跳转到商品详情页
const goToDetail = (id) => {
  router.push(`/commodity/${id}`)
}

//处理图片url
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = SERVER_BASE_URL;
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  }

  return fullUrl;
}

// 处理全局滚动事件
const handleIndexScroll = () => {
  // console.log('CommodityView接收到IndexView的滚动事件')
  loadMore()
}

onMounted(async () => {
  await fetchCommodities()
  // 添加全局事件监听
  window.addEventListener('index-scroll-bottom', handleIndexScroll)
})

onUnmounted(() => {
  // 移除全局事件监听，防止内存泄漏
  window.removeEventListener('index-scroll-bottom', handleIndexScroll)
})

// 暴露loadMore方法供父组件调用
defineExpose({
  loadMore
})
</script>

<template>
  <div class="commodity-container">
    
    <div ref="listWrapper" id="listContainer" class="commodity-grid">
      <transition-group name="commodity-fade">
          <div
              v-for="item in commodities"
              :key="item.id"
              class="commodity-card"
              @click="goToDetail(item.id)"
          >
            <div class="commodity-image">
              <el-image
                  :src="item.image && item.image.length > 0 ? getImgUrl(item.image[0]) : ''"
                  fit="cover"
                  lazy
              >
                <template #error>
                  <div class="image-error">暂无图片</div>
                </template>
              </el-image>
              <div class="card-overlay">
                <span class="view-details">查看详情</span>
              </div>
            </div>
            <div class="commodity-info">
              <h3 class="commodity-name" :title="item.name">{{ item.name }}</h3>
              <div class="commodity-price">¥ {{ item.price }}</div>
              <div class="commodity-footer">
                <div class="commodity-sales">销量: {{ item.salesVolume || 0 }}</div>
                <div class="commodity-stock" v-if="item.stock">库存: {{ item.stock }}</div>
              </div>
            </div>
          </div>
      </transition-group>
    </div>
    
    <!-- 加载状态指示 -->
    <div class="loading-container" v-if="loading || noMore">
      <el-skeleton :loading="loading" animated :count="1" v-if="loading">
        <template #template>
          <div style="display:flex; justify-content:center; padding:20px;">
            <el-skeleton-item variant="p" style="width: 20%; height: 24px; margin: 0 auto;" />
          </div>
        </template>
      </el-skeleton>
      <p v-if="loading" class="loading-text">正在加载更多商品...</p>
      <p v-if="noMore && commodities.length > 0" class="no-more-text">已经到底啦~</p>
      <p v-if="noMore && commodities.length === 0" class="no-more-text">暂无商品数据</p>
    </div>
  </div>
</template>

<style scoped>
.commodity-container {
  width: 100%;
  min-height: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden; /* 防止滚动条出现 */
}

.commodity-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  row-gap: 15px; /* 行间距 */
  column-gap: 10px; /* 列间距 */
  overflow: hidden; /* 修改为hidden，防止图片内容溢出 */
  min-height: 200px; /* 确保有足够的高度触发滚动 */
}

@media (max-width: 768px) {
  .commodity-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 15px;
  }
}

/* 禁用所有滚动条 */
:deep(::-webkit-scrollbar) {
  width: 0;
  height: 0;
  display: none;
}

:deep(*) {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.commodity-card {
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  height: 100%;
  overflow: hidden;
  margin: 0;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border: 1px solid #d9dbdd;
  padding: 5px;
}

.commodity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.2);
}

.commodity-card:hover .card-overlay {
  opacity: 1;
}

.commodity-image {
  height: 280px;
  overflow: hidden;
  border-radius: 10px 10px 0 0;
  position: relative;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.view-details {
  color: white;
  font-size: 16px;
  font-weight: 500;
  padding: 6px 14px;
  border-radius: 20px;
  background-color: rgba(64, 158, 255, 0.8);
}

.el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.commodity-card:hover .el-image {
  transform: scale(1.05);
}

.image-error {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.commodity-info {
  padding: 10px 3px;
  padding-bottom: 5px;
  font-size: 15px;
  background-color: #fff;
  border-radius: 0 0 10px 10px;
}

.commodity-name {
  font-size: 15px;
  margin: 0 0 6px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
  font-weight: 500;
}

.commodity-price {
  font-size: 18px;
  color: #ff6700;
  font-weight: bold;
  margin-bottom: 3px;
}

.commodity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.commodity-sales, .commodity-stock {
  font-size: 12px;
  color: #909399;
}

.loading-container {
  text-align: center;
  padding: 20px 0;
}

.loading-text {
  color: #409EFF;
  font-size: 14px;
  margin-top: 8px;
}

.no-more-text {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
  position: relative;
  display: inline-block;
  padding: 0 20px;
}

.no-more-text::before,
.no-more-text::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 50px;
  height: 1px;
  background-color: #EBEEF5;
}

.no-more-text::before {
  left: -40px;
}

.no-more-text::after {
  right: -40px;
}

.load-more-container {
  text-align: center;
  margin: 20px 0;
}

/* 商品卡片动画 */
.commodity-fade-enter-active,
.commodity-fade-leave-active {
  transition: all 0.5s ease;
}

.commodity-fade-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.commodity-fade-leave-to {
  opacity: 0;
}
</style>